package se.slackers.floatingtableheader.client.generator;

import com.google.gwt.dom.client.Node;
import com.google.gwt.user.client.Element;

public class TRClassHeaderGenerator extends AbstractHeaderGenerator {
	private final String[] validClasses;

	public TRClassHeaderGenerator(final String... validClasses) {
		this.validClasses = validClasses;
	}

	@Override
	public Element create(final Element root) {
		final Element clonedRoot = (Element) root.cloneNode(false);
		for (int i = 0; i < root.getChildCount(); i++) {
			final Node child = root.getChild(i);
			if (child.getNodeType() != Node.ELEMENT_NODE) {
				// Append all non-element nodes
				clonedRoot.appendChild(child.cloneNode(true));
			} else {
				final String name = child.getNodeName();
				if (isTHEAD(name) || isTBODY(name)) {
					// recurse into THEAD and TBODY
					clonedRoot.appendChild(create((Element) child));
				} else if (isTR(name)) {
					// check if the TR contains any one the classes in validClasses
					final String className = ((Element) child).getClassName();
					for (final String clazz : validClasses) {
						if (className.indexOf(clazz) >= 0) {
							clonedRoot.appendChild(cloneWithSize(child));
							break;
						}
					}
				}
			}
		}
		return clonedRoot;
	}
}
